import 'dart:io';

import 'package:permission_handler/permission_handler.dart';
import 'package:share_fit/app/controllers/base/base_controller.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/ute/uteped_const.dart';
import 'package:share_fit/generated/locales.g.dart';

import 'sms_remind_state.dart';

class SmsRemindLogic extends BaseController {
  final SmsRemindState state = SmsRemindState();
  static const methodSetSmsRemindEnable = "setSmsRemindEnable";

  Future<void> updateSmsSwitch(bool value) async {
    if (!await _checkPermission()) {
      return;
    }
    showLoading();
    state.smsSwitchValue = value;
    bRemoteReqAsync(methodSetSmsRemindEnable, {UTEPedConst.keyEnable: value})
        .then((success) => _onSetSmsRemindEnable(success, value));
  }

  void _onSetSmsRemindEnable(success, value) {
    cancelLoading();
    if (success) {
      save(methodSetSmsRemindEnable, value);
    }
    else {
      state.smsSwitchValue = !value;
    }
    update(['sms_remind_switch']);
  }

  @override
  Future<void> onReady() async {
    _checkPermission();
    super.onReady();
  }

  Future<bool> _checkPermission() async {
    var hasPermission = true;
    if (Platform.isAndroid) {
      hasPermission = await Permission.sms.isGranted;
      if (!hasPermission) {
        var value = await Permission.sms.request();
        if(!value.isGranted && Platform.isAndroid){
          showPermissionDialog(LocaleKeys.sms_permission_tips.ts);
        }
      }
    }

    return hasPermission;
  }

  @override
  String getRemotePath() {
    return UTEPedConst.pathContact;
  }

  @override
  String getStoragePath() {
    return UTEPedConst.pathDevice;
  }

  @override
  Future<void> initState() async {
    state.smsSwitchValue = read(methodSetSmsRemindEnable, defaultValue: false);
    if (Platform.isAndroid) {
      var granted = await Permission.sms.request().isGranted;
      if (!granted) {
        state.smsSwitchValue = false;
      }
    }
  }

  @override
  void onRemoteEvent(event, method) {
    if (method == UTEPedConst.methodCheckPermissions) {
      var success = event[UTEPedConst.keyResult];
      var type = event[UTEPedConst.keyValue];
      if (success && type == UTEPedConst.permissionSms) {
        state.smsSwitchValue = true;
        _onSetSmsRemindEnable(success, true);
      }
    }
  }
}
